package com.service.approval.interceptor;

import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class ApprovalIntercepterChain {

	private final List<ApprovalIntercepter> intercepters = new LinkedList<ApprovalIntercepter>();

	public ApprovalIntercepterChain() {
		// this.intercepters = new LinkedList<ApprovalIntercepter>();
	}

	/**
	 * 注入消息处理器
	 * 
	 * @param injectedHandlers 消息处理器
	 */
	@Autowired(required = false)
	public void setIntercepters(ApprovalIntercepter... intercepterSources) {
		intercepters.clear();
		//安装实现类的首字母进行排序后然后新增到集合中
		Map<String, ApprovalIntercepter> m = new HashMap<String, ApprovalIntercepter>();
		String[] firstStrs = new String[intercepterSources.length];
		for (int i = 0; i < intercepterSources.length; i++) {
			ApprovalIntercepter approvalIntercepter = intercepterSources[i];
			String firstStr = approvalIntercepter.getClass().getSimpleName().substring(0, 1);
			m.put(firstStr, approvalIntercepter);
			firstStrs[i] = firstStr;
		}
		Arrays.sort(firstStrs);
		for (String key : firstStrs) {
			ApprovalIntercepter approvalIntercepter = m.get(key);
			addIntercepter(approvalIntercepter);
		}
//		for (ApprovalIntercepter approvalIntercepter : intercepterSources) {
//			String firstStr = approvalIntercepter.getClass().getSimpleName().substring(0, 1);
//			m.put(firstStr, approvalIntercepter);
//		}
		//
	}

	public ApprovalIntercepterChain addIntercepter(ApprovalIntercepter intercepter) {
		intercepters.add(intercepter);
		return this;
	}

	public ApprovalContext executeIntercepter(ApprovalContext approvalContext) {
		for (ApprovalIntercepter approvalIntercepter : intercepters) {
			approvalIntercepter.execute(approvalContext);
		}
		return approvalContext;
	}
}
